import 'package:flutter/material.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:form_builder_validators/form_builder_validators.dart';
import 'package:go_router/go_router.dart';
import 'package:merchants/models/merchant.dart';
import 'package:merchants/providers/providers.dart';

class MerchantEditScreen extends ConsumerStatefulWidget {
  final String merchantId;

  const MerchantEditScreen({super.key, required this.merchantId});

  @override
  ConsumerState<MerchantEditScreen> createState() => _MerchantEditScreenState();
}

class _MerchantEditScreenState extends ConsumerState<MerchantEditScreen> {
  final _formKey = GlobalKey<FormBuilderState>();
  bool _isSubmitting = false;
  bool? _isAppSecretGenerated;

  Future<Merchant> _loadMerchant() {
    return ref.read(merchantServiceProvider).getMerchantById(widget.merchantId);
  }

  Future<void> _submitForm(Merchant merchant) async {
    if (_formKey.currentState?.saveAndValidate() ?? false) {
      setState(() {
        _isSubmitting = true;
      });

      try {
        final formData = _formKey.currentState!.value;

        final updatedMerchant = Merchant(
          id: merchant.id,
          name: formData['name'],
          merchantName: formData['merchant_name'],
          miniProgramName: formData['mini_program_name'],
          legalPersonName: formData['legal_person_name'],
          legalPersonPhone: formData['legal_person_phone'],
          appid: formData['appid'],
          mchid: formData['mchid'],
          status: formData['status'],
          address: formData['address'],
          createdAt: merchant.createdAt,
          updatedAt: DateTime.now().millisecondsSinceEpoch,
        );

        await ref
            .read(merchantServiceProvider)
            .updateMerchant(widget.merchantId, updatedMerchant);

        if (mounted) {
          ScaffoldMessenger.of(
            context,
          ).showSnackBar(const SnackBar(content: Text('商户信息更新成功')));
          context.go('/tabs');
        }
      } catch (e) {
        if (mounted) {
          ScaffoldMessenger.of(
            context,
          ).showSnackBar(SnackBar(content: Text('更新失败：${e.toString()}')));
        }
      } finally {
        if (mounted) {
          setState(() {
            _isSubmitting = false;
          });
        }
      }
    }
  }

  Future<bool> _checkAppSecretGenerated(String merchantId) async {
    try {
      final has = await ref
          .read(merchantSecretServiceProvider)
          .checkSecret(merchantId);
      return has;
    } catch (e) {
      return false;
    }
  }

  Future<void> _generateAppSecret(Merchant merchant) async {
    if (_isAppSecretGenerated == true) {
      // 检查当前状态
      final shouldGenerate = await showDialog<bool>(
        context: context,
        builder:
            (context) => AlertDialog(
              title: const Text('警告'),
              content: const Text(
                '更新 appSecret 将影响商户后台的正常运行，需要重新调整打包。请确认是否在非运营时间执行此操作？',
              ),
              actions: [
                TextButton(
                  onPressed: () => Navigator.of(context).pop(false),
                  child: const Text('取消'),
                ),
                TextButton(
                  onPressed: () => Navigator.of(context).pop(true),
                  child: const Text('确认生成'),
                ),
              ],
            ),
      );

      if (shouldGenerate != true) return;
    }

    setState(() {
      _isSubmitting = true;
    });

    try {
      final success = await ref
          .read(merchantSecretServiceProvider)
          .createSecret(merchant.id!);
      if (mounted) {
        if (success) {
          setState(() {
            _isAppSecretGenerated = true; // 更新状态
          });
          ScaffoldMessenger.of(
            context,
          ).showSnackBar(const SnackBar(content: Text('appSecret 生成成功')));
        } else {
          ScaffoldMessenger.of(
            context,
          ).showSnackBar(const SnackBar(content: Text('appSecret 生成失败')));
        }
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('生成 appSecret 失败：${e.toString()}')),
        );
      }
    } finally {
      if (mounted) {
        setState(() {
          _isSubmitting = false;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('编辑商户')),
      body: FutureBuilder<Merchant>(
        future: _loadMerchant(),
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return const Center(child: CircularProgressIndicator());
          }

          if (snapshot.hasError) {
            return Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text('加载商户失败：${snapshot.error}'),
                  const SizedBox(height: 16),
                  ElevatedButton(
                    onPressed: () => context.go('/tabs'),
                    child: const Text('返回'),
                  ),
                ],
              ),
            );
          }

          if (!snapshot.hasData) {
            return const Center(child: Text('没有找到商户数据'));
          }

          final merchant = snapshot.data!;

          // 嵌套 FutureBuilder 加载 appSecret 状态
          return FutureBuilder<bool>(
            future: _checkAppSecretGenerated(widget.merchantId),
            builder: (context, appSecretSnapshot) {
              if (appSecretSnapshot.connectionState ==
                  ConnectionState.waiting) {
                return const Center(child: CircularProgressIndicator());
              }

              if (appSecretSnapshot.hasError) {
                return Center(
                  child: Text('加载 appSecret 状态失败：${appSecretSnapshot.error}'),
                );
              }

              if (!appSecretSnapshot.hasData) {
                return const Center(child: Text('无法加载 appSecret 状态'));
              }

              _isAppSecretGenerated = appSecretSnapshot.data!; // 更新状态

              return SingleChildScrollView(
                padding: const EdgeInsets.all(20),
                child: FormBuilder(
                  key: _formKey,
                  initialValue: {
                    'name': merchant.name,
                    'merchant_name': merchant.merchantName,
                    'mini_program_name': merchant.miniProgramName,
                    'legal_person_name': merchant.legalPersonName,
                    'legal_person_phone': merchant.legalPersonPhone,
                    'appid': merchant.appid,
                    'mchid': merchant.mchid,
                    'status': merchant.status,
                    'address': merchant.address,
                  },
                  child: Column(
                    children: [
                      const SizedBox(height: 20),
                      FormBuilderTextField(
                        name: 'name',
                        decoration: const InputDecoration(
                          labelText: '商户名/店名',
                          prefixIcon: Icon(Icons.store),
                          border: OutlineInputBorder(),
                        ),
                        validator: FormBuilderValidators.compose([
                          FormBuilderValidators.required(),
                          FormBuilderValidators.maxLength(50),
                        ]),
                      ),
                      const SizedBox(height: 16),
                      FormBuilderTextField(
                        name: 'merchant_name',
                        decoration: const InputDecoration(
                          labelText: '商家名称',
                          prefixIcon: Icon(Icons.business),
                          border: OutlineInputBorder(),
                        ),
                        validator: FormBuilderValidators.compose([
                          FormBuilderValidators.required(),
                          FormBuilderValidators.maxLength(100),
                        ]),
                      ),
                      const SizedBox(height: 16),
                      FormBuilderTextField(
                        name: 'mini_program_name',
                        decoration: const InputDecoration(
                          labelText: '小程序名称',
                          prefixIcon: Icon(Icons.apps),
                          border: OutlineInputBorder(),
                        ),
                        validator: FormBuilderValidators.compose([
                          FormBuilderValidators.required(),
                          FormBuilderValidators.maxLength(20),
                        ]),
                      ),
                      const SizedBox(height: 16),
                      FormBuilderTextField(
                        name: 'legal_person_name',
                        decoration: const InputDecoration(
                          labelText: '法人姓名',
                          prefixIcon: Icon(Icons.person),
                          border: OutlineInputBorder(),
                        ),
                        validator: FormBuilderValidators.compose([
                          FormBuilderValidators.required(),
                          FormBuilderValidators.maxLength(50),
                        ]),
                      ),
                      const SizedBox(height: 16),
                      FormBuilderTextField(
                        name: 'legal_person_phone',
                        decoration: const InputDecoration(
                          labelText: '法人电话',
                          prefixIcon: Icon(Icons.phone),
                          border: OutlineInputBorder(),
                        ),
                        keyboardType: TextInputType.phone,
                        validator: FormBuilderValidators.compose([
                          FormBuilderValidators.required(),
                          FormBuilderValidators.match(
                            RegExp(r'^[0-9]{11}$'),
                            errorText: '请输入11位手机号',
                          ),
                        ]),
                      ),
                      const SizedBox(height: 16),
                      FormBuilderTextField(
                        name: 'appid',
                        decoration: const InputDecoration(
                          labelText: '小程序 AppID',
                          prefixIcon: Icon(Icons.apps),
                          border: OutlineInputBorder(),
                        ),
                        validator: FormBuilderValidators.compose([
                          FormBuilderValidators.required(),
                          FormBuilderValidators.minLength(10),
                          FormBuilderValidators.maxLength(100),
                        ]),
                      ),
                      const SizedBox(height: 16),
                      FormBuilderTextField(
                        name: 'mchid',
                        decoration: const InputDecoration(
                          labelText: '微信支付商户号',
                          prefixIcon: Icon(Icons.payment),
                          border: OutlineInputBorder(),
                        ),
                        validator: FormBuilderValidators.compose([
                          FormBuilderValidators.required(),
                          FormBuilderValidators.minLength(8),
                          FormBuilderValidators.maxLength(20),
                        ]),
                      ),
                      const SizedBox(height: 16),
                      FormBuilderDropdown<String>(
                        name: 'status',
                        decoration: const InputDecoration(
                          labelText: '状态',
                          prefixIcon: Icon(Icons.info),
                          border: OutlineInputBorder(),
                        ),
                        items: const [
                          DropdownMenuItem(
                            value: 'pending',
                            child: Text('待审核'),
                          ),
                          DropdownMenuItem(value: 'active', child: Text('已激活')),
                          DropdownMenuItem(
                            value: 'inactive',
                            child: Text('已禁用'),
                          ),
                        ],
                        validator: FormBuilderValidators.compose([
                          FormBuilderValidators.required(),
                        ]),
                      ),
                      const SizedBox(height: 16),
                      FormBuilderTextField(
                        name: 'address',
                        decoration: const InputDecoration(
                          labelText: '店铺地址',
                          prefixIcon: Icon(Icons.location_on),
                          border: OutlineInputBorder(),
                        ),
                        validator: FormBuilderValidators.compose([
                          FormBuilderValidators.maxLength(100),
                        ]),
                      ),
                      const SizedBox(height: 16),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text(
                            _isAppSecretGenerated == true
                                ? 'appSecret: 已生成'
                                : 'appSecret: 未生成',
                            style: const TextStyle(fontSize: 16),
                          ),
                          SizedBox(
                            width: 100,
                            child: ElevatedButton(
                              onPressed:
                                  _isSubmitting
                                      ? null
                                      : () => _generateAppSecret(merchant),
                              style: ElevatedButton.styleFrom(
                                backgroundColor: Colors.grey[300],
                                foregroundColor: Colors.black,
                                padding: const EdgeInsets.symmetric(
                                  vertical: 16,
                                ),
                                shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(12),
                                ),
                              ),
                              child:
                                  _isSubmitting
                                      ? const SizedBox(
                                        width: 20,
                                        height: 20,
                                        child: CircularProgressIndicator(
                                          strokeWidth: 2,
                                        ),
                                      )
                                      : const Text(
                                        '生成',
                                        style: TextStyle(
                                          fontSize: 16,
                                          fontWeight: FontWeight.w600,
                                        ),
                                      ),
                            ),
                          ),
                        ],
                      ),
                      const SizedBox(height: 24),
                      SizedBox(
                        width: double.infinity,
                        child: ElevatedButton(
                          onPressed:
                              _isSubmitting
                                  ? null
                                  : () => _submitForm(merchant),
                          style: ElevatedButton.styleFrom(
                            backgroundColor: Theme.of(context).primaryColor,
                            foregroundColor: Colors.white,
                            padding: const EdgeInsets.symmetric(vertical: 16),
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(12),
                            ),
                            elevation: 0,
                          ),
                          child:
                              _isSubmitting
                                  ? const SizedBox(
                                    width: 20,
                                    height: 20,
                                    child: CircularProgressIndicator(
                                      strokeWidth: 2,
                                      valueColor: AlwaysStoppedAnimation<Color>(
                                        Colors.white,
                                      ),
                                    ),
                                  )
                                  : const Text(
                                    '保存',
                                    style: TextStyle(
                                      fontSize: 16,
                                      fontWeight: FontWeight.w600,
                                    ),
                                  ),
                        ),
                      ),
                    ],
                  ),
                ),
              );
            },
          );
        },
      ),
    );
  }
}
